#include"networkmanager.h"
#include"Json/reader.h"
#include"tool.h"

using namespace Json;

DEFINE_SINGLE_ATTRIBUTES(NetWorkManager);

NetWorkManager::NetWorkManager()
{

}

void NetWorkManager::startServer()
{
    if(!m_socketManager.StartServer())
    {
        cout<<"start server success!"<<sizeof(int)<<endl;
    }
    else
    {
        cout<<m_socketManager.GetLastError()<<endl;
        cout<<"start server failed!"<<endl;
    }
}

Slot* NetWorkManager::add(const int & messageId, const EventHandler& evHandler)
{
    if (m_signals.find(messageId) != m_signals.end())
        return m_signals[messageId].add(evHandler);
    else
    {
        m_signals[messageId] = Signal();
        return m_signals[messageId].add(evHandler);
    }
}

Slot * NetWorkManager::add(const int & messageId, const std::function<void(Json::Value&)>& func)
{
    if (m_signals.find(messageId) != m_signals.end())
        return m_signals[messageId].add(func);
    else
    {
        m_signals[messageId] = Signal();
        return m_signals[messageId].add(func);
    }
}

void NetWorkManager::dispatch(const int & messageId,Json::Value& message)
{
    cout<<"NetWorkManager::dispatch"<<message.toStyledString()<<endl;
    m_signals[messageId].dispatch(message);
}

void NetWorkManager::send(const int& fd,const int & messageId, const std::map<std::string, std::string>& msg)
{
    Json::Value value;
    value["MessageId"] = messageId;
    for (auto var : msg)
    {
        if (isNum(var.second))
            value[var.first] = std::stof(var.second);
        else
            value[var.first] = var.second;
    }
    std::string out = value.toStyledString();
    m_socketManager.SendMsg(fd,(char*)out.c_str(), out.length());
}

void NetWorkManager::send(const int& fd,const int & messageId, Json::Value& msg)
{
    msg["MessageId"]=messageId;
    std::string out=msg.toStyledString();
    cout<<"send:"<<out<<endl;
    m_socketManager.SendMsg(fd,(char*)out.c_str(),out.length());
}
